package com.huiquan.vocab.controller;

import com.huiquan.analysis.domain.User;
import com.huiquan.foundation.constant.TabID;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.RequestParamUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.vocab.service.VocabElementService;
import com.huiquan.vocab.service.VocabElementTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class VocabElementController {

    @Autowired
    private VocabElementService vocabElementService;
    @Autowired
    private VocabElementTService vocabElementTService;

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/vocab/element_list.htm")
    public ModelAndView list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String tabid = req.getParameter("tabid");
        Integer flag = 0;
        Integer source = 1;

        // 维护页面参数到session
        Map<String, Object> pageParam;
        if (tabid != null && !tabid.isEmpty()) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("start", "1");
            pageParam.put("exactSearchFlag", "0");

            flag = TabID.getElementFlagByTabID(tabid);
            pageParam.put("flag", flag.toString());

            // 如果是诊断模块，则将数据来源设置为2
            if (TabID.isAnalysisDi(tabid)) {
                source = 2;
            }
            pageParam.put("source", source.toString());

            req.getSession().setAttribute("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
            String flagStr = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "flag");
            flag = Integer.parseInt(flagStr);
            source = Integer.parseInt(RequestParamUtil.getParamByRequestOrSession(req, pageParam, "source"));
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "start");
        String keyword = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "keyword");
        String propertyKey = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "propertyKey");
        String exactSearchFlag = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "exactSearchFlag");
        String replaceTypeKey = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "replaceTypeKey");
        String countPerPageStr = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "countPerPage");

        return vocabElementService.list(start, keyword, flag, propertyKey, exactSearchFlag, replaceTypeKey,
                countPerPageStr, source);
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_mapping_slang.do")
    public ReturnData setMappingSlang(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        String id = req.getParameter("id");
        String slang = req.getParameter("slang");
        return vocabElementService.mappingSlang(id, slang, user);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/vocab/element_replace_list.htm")
    public ModelAndView elementReplace(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String tabid = req.getParameter("tabid");

        // 维护页面参数到session
        Map<String, Object> pageParam;
        if (tabid != null && !tabid.isEmpty()) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("start", "1");
            pageParam.put("exactSearchFlag", "0");

            req.getSession().setAttribute("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "start");
        String keyword = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "keyword");
        String propertyKey = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "propertyKey");
        String exactSearchFlag = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "exactSearchFlag");
        String replaceTypeKey = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "replaceTypeKey");
        String countPerPage = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "countPerPage");

        return vocabElementService.elementReplace(start, keyword, propertyKey, exactSearchFlag, replaceTypeKey,
                countPerPage);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/vocab/element_slang_list.htm")
    public ModelAndView elementSlang(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String tabid = req.getParameter("tabid");

        // 维护页面参数到session
        Map<String, Object> pageParam;
        if (tabid != null && !tabid.isEmpty()) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("start", "1");
            pageParam.put("exactSearchFlag", "0");

            req.getSession().setAttribute("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "start");
        String keyword = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "keyword");
        String propertyKey = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "propertyKey");
        String exactSearchFlag = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "exactSearchFlag");
        String countPerPageStr = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "countPerPage");

        return vocabElementService.elementSlang(start, keyword, propertyKey, exactSearchFlag, countPerPageStr);
    }

    @RequestMapping(value = "/vocab/element_export.htm")
    public void export(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String property = req.getParameter("property");
        String keyword = req.getParameter("keyword");

        vocabElementService.elementExport(property, keyword, resp);
    }

    @RequestMapping(value = "/vocab/element_export_sex_age.htm")
    public void exportSexAge(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        vocabElementService.exportSexAge(resp);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/vocab/element_sex_age_list.htm")
    public ModelAndView elementSexAge(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String tabid = req.getParameter("tabid");

        // 维护页面参数到session
        Integer status = 0;
        Map<String, Object> pageParam;
        if (tabid != null && !tabid.isEmpty()) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("start", "1");
            pageParam.put("status", status.toString());
            pageParam.put("exactSearchFlag", "0");

            req.getSession().setAttribute("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
            String statusStr = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "status");
            status = Integer.parseInt(statusStr);
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "start");
        String keyword = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "keyword");
        String propertyKey = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "propertyKey");
        String exactSearchFlag = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "exactSearchFlag");
        String sexKey = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "sexKey");
        String countPerPageStr = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "countPerPage");

        return vocabElementService.elementSexAgeList(start, keyword, status, propertyKey, sexKey, exactSearchFlag,
                countPerPageStr);
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_set_sex.do")
    public ReturnData setSex(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        String id = req.getParameter("id");
        String sex = req.getParameter("sex");
        return vocabElementService.setSex(id, sex, user);
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_set_age.do")
    public ReturnData setAge(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        String id = req.getParameter("id");
        String age = req.getParameter("age");
        Boolean flag = Boolean.parseBoolean(req.getParameter("flag"));
        return vocabElementService.setAge(id, age, flag, user);
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_submit_sex_age.do")
    public ReturnData submitSexAge(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        String ids = req.getParameter("ids");
        return vocabElementService.submitSexAge(ids, user);
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/vocab/element_check_page.do")
    public ReturnData checkPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        String ids = req.getParameter("ids");
        String flag = req.getParameter("flag");
        String replaceVocabs = req.getParameter("replaceVocabs");
        String replaceProp = req.getParameter("replaceProp");
        String splitWord = req.getParameter("splitWord");


        try {
            return vocabElementService.checkPage(ids.substring(0, ids.length() - 1).split(","), flag.substring(0, flag.length() - 1).split(","), replaceVocabs.substring(0, replaceVocabs.length() - 1).split(",", -1), replaceProp.substring(0, replaceProp.length() - 1).split(",", -1), splitWord.substring(0, splitWord.length() - 1).split("@", -1), user);
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().startsWith("校验结果")) {
                ReturnCode rc = ReturnCode.ELEMENT_CHECK_PAGE_ERROR;
                rc.setDesc(e.getMessage());
                return ReturnUtil.fail(rc);
            } else {
                throw e;
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_change_time_quantization.do")
    public ReturnData elementChangeQuantization(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        User user = (User) req.getSession().getAttribute("user");
        String id = req.getParameter("id"); // 小词的id
        String quantization = req.getParameter("quantization"); // 量化值

        return vocabElementTService.elementChangeQuantization(id, quantization, user);
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_t_init_quantization.do")
    public void elementTimeQuantizationInit(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        // 初始化量化
        vocabElementTService.elementTimeQuantizationInit();
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_t_testn.do")
    public void elementTimeQuantizationTest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 初始化量化
        vocabElementTService.elementTimeQuantizationTest();
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_r_add_synonymy.do")
    public ReturnData elementRAddSynonymy(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        User user = (User) req.getSession().getAttribute("user");
        String id = req.getParameter("id"); // 小词的ids
        String std = req.getParameter("name"); // 标准词

        return vocabElementService.elementRAddSynonymy(id, std, user);
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_r_check_analysis.do")
    public ReturnData elementRCheckAnalysis(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        User user = (User) req.getSession().getAttribute("user");
        String id = req.getParameter("id"); // 小词的id
        String analysisFlag = req.getParameter("analysisFlag"); // r元素的标注标志

        return vocabElementService.elementRCheckAnalysis(id, analysisFlag, user);
    }

    @ResponseBody
    @RequestMapping(value = "/vocab/element_init_syn_sex_age.do")
    public ReturnData elementInitSynSexAge(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        vocabElementService.initSexAgeSynonymy();
        return ReturnUtil.success();
    }
}
